/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ep.m002.ui.controllers;

import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import ep.libs.implementations.AbstractModule;
import ep.m002.bl.BL002Controller;
import ep.persistence.controllers.T001UserJpaController;
import ep.persistence.entities.T001User;
import ep.persistence.entities.T002Doctor;
import ep.persistence.entities.T005Patient;
import javax.persistence.Query;

/**
 *
 * @author skyr
 */
public class M002Controller {

    private BL002Controller bL002Controller;
    private T005Patient patient;
    private AbstractModule module;

    public M002Controller(AbstractModule module) {
        bL002Controller = new BL002Controller();
        this.module = module;
    }

    public T005Patient getPatient() {
        return patient;
    }

    public BeanItem<T005Patient> getPatientDataSource(String amka) {
        patient = bL002Controller.getPatientByAmka(amka);
        if (patient == null) {
            return null;
        } else {
            BeanItem<T005Patient> beanItem = new BeanItem<T005Patient>(patient);
            return beanItem;
        }
    }

    public boolean isDoctorEligible() {
        T002Doctor doctor = findDoctor();
        try {
            return doctor.getT004Insurances().contains(patient.getT004Insurance());
        } catch (Exception e) {
            return false;
        }

    }

    public String getAmkaByPatientObject(Object patientObj) {
        T005Patient tp = (T005Patient) patientObj;
        return tp.getAmka();
    }

    private T002Doctor findDoctor() {
        String username = (String) ((WebApplicationContext) module.getApplication().getContext()).getHttpSession().getAttribute("username");
        T001UserJpaController jpaController = new T001UserJpaController();
        Query query = jpaController.getEntityManager().createNamedQuery("T001User.findByUsername", T001User.class);
        query.setParameter("username", username);
        T001User user = (T001User) query.getResultList().iterator().next();
        if (!user.getT002DoctorCollection().isEmpty()) {
            return user.getT002DoctorCollection().iterator().next();
        }
        return null;
    }
}
